var sourceType = [
  ['camera'],
  ['album'],
  ['camera', 'album']
]
var sizeType = [
  ['compressed'],
  ['original'],
  ['compressed', 'original']
]
// pages/check_list/check_list.js
var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
const {
  requestDataparams
} = require('../../utils/request.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    imageList: [],
    imagepreList: [],
    sources: '',
    address: '',
    addressshow: true,
    applicantId: '',
    applicationName: '',
    applicantPhone: '',
    areaId: '',
    address: '',
    remark: '',
    planningTime: '请选择预约时间(必填)',
    pics: [],
    sourceTypeIndex: 0,
    sizeTypeIndex: 0,
    detailInfo: {},
    listarea: ['请选择', 'A区', 'B区', 'C区', 'D区'],
    listareaid: [null, 'personal_use', 'business_use', 'b2p_use', 'rental_use'],
    listareaindex: 0,
    listbuild: ['请选择'],
    listbuildid: [null],
    listbuildindex: 0,
    listfloor: [''],
    listfloorid: [],
    listfloorindex: 0,
    areslenth: '',
    buildid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userInfo = wx.getStorageSync("USER_INFO");
    var nickName = wx.getStorageSync("nickName");
    this.setData({
      applicationName: nickName,
      applicantPhone: userInfo.bindPhone,
    });

    var applicantId = wx.getStorageSync("id");
    this.data.applicantId = applicantId;
    // this.loadBuildings()
    this.loadAreas();
    this.loadbuild();
  },
  chooseImage_album: function (e) {
    var that = this;
    wx.chooseImage({
      sourceType: sourceType[2],
      count: 9,
      success: function (res) {
        var imgsrc = res.tempFiles;
        var imgsrc2 = res.tempFiles;
        var imgsrc3 = res.tempFilePaths;
        var pics = that.data.pics.concat(imgsrc);
        var imageList = that.data.imageList.concat(imgsrc2);
        var imagepreList = that.data.imagepreList.concat(imgsrc3);
        that.setData({
          pics: pics,
          imageList: imageList,
          imagepreList: imagepreList
        })

      }
    })
  },
  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    var src = e.currentTarget.dataset.src;
    const images = this.data.imagepreList;

    wx.previewImage({
      current: src, //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },

  // previewImage(event) {
  //   var src = event.currentTarget.dataset.src; //获取data-src
  //   var imgList = event.currentTarget.dataset.list; //获取data-list

  //   wx.previewImage({
  //     current: src, // 当前显示图片的http链接
  //     urls: imgList // 需要预览的图片http链接列表

  //   })
  // },
  previewImage(event) {

    var src = event.currentTarget.dataset.src; //获取data-src
    var imgList = this.data.imageList //获取data-list

    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表

    })
  },
  delect(e) {
    var pics = this.data.pics;
    var imageList = this.data.imageList;
    var imagepreList = this.data.imagepreList;
    var index = e.currentTarget.dataset.idx;
    pics.splice(index, 1);
    imageList.splice(index, 1);
    imagepreList.splice(index, 1);
    this.setData({
      pics: pics,
      imageList: imageList,
      imagepreList: imagepreList
    });
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },
  changeDate: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(
      this.data
    );
  },
  //选择区域
  changeUsedType: function (e) {
    this.data.areaId = this.data.listareaid[e.detail.value];
    this.data.listareaindex = e.detail.value;
    // if (e.detail.value < this.data.areslenth) {
    //   this.setData({
    //     addressshow: false
    //   })
    // }
    this.setData(this.data);

  },
  changebuild: function (e) {
    this.data.buildid = this.data.listbuildid[e.detail.value];
    this.data.listbuildindex = e.detail.value;
    // if (e.detail.value < this.data.areslenth) {
    //   this.setData({
    //     addressshow: false
    //   })
    // }
    this.setData(this.data);
    this.loadFloor();
  },
  changefloor: function (e) {
    if (!this.data.buildid || this.data.buildid == 'null' || this.data.buildid == null) {
      util.showModal('请先选择楼栋');
      return
    }
    this.data.floorId = this.data.listfloorid[e.detail.value];
    this.data.listfloorindex = e.detail.value;
    this.setData(this.data);

  },
  //加载楼栋
  loadbuild() {
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/buildings',
      success(res) {
        let listbuild = [];
        listbuild.push("请选择楼栋")
        let listbuildid = [];
        listbuildid.push("null")
        if (res.data.code == 0) {
          for (let item of res.data.data) {
            listbuild.push(item.name)
            listbuildid.push(item.id)
          }
          that.data.listbuild = listbuild;
          that.data.listbuildid = listbuildid;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  loadFloor() {
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/floors?buildingId=' + that.data.buildid,
      success(res) {
        let listfloor = [];
        listfloor.push("请选择房楼层")
        let listfloorid = [];
        listfloorid.push("null")
        if (res.data.code == 0) {
          for (let item of res.data.data) {
            listfloor.push(item.name)
            listfloorid.push(item.id)
          }
          that.data.listfloor = listfloor;
          that.data.listfloorid = listfloorid;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: res.data.mesage,
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data.message
        })
      }
    })
  },

  //加载区域
  loadAreas() {
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/areas',
      success(res) {
        let listarea = [];
        listarea.push("请选择区域")
        let listareaid = [];
        listareaid.push("null")
        if (res.data.code == 0) {
          that.data.areslenth = res.data.data.length;
          for (let item of res.data.data) {
            listarea.push(item.name)
            listareaid.push(item.id)
          }
          that.data.listarea = listarea;
          that.data.listareaid = listareaid;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  //加载区域
  loadBuildings() {
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/buildings',
      success(res) {
        let listarea = [];
        let listareaid = [];

        if (res.data.code == 0) {
          for (let item of res.data.data) {
            listarea.push(item.name)
            listareaid.push(item.id)
          }
          that.data.listarea = that.data.listarea.concat(listarea);
          that.data.listareaid = that.data.listareaid.concat(listareaid);
          that.setData(that.data);
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  submitRepair() {

    var that = this;
    if (!that.data.areaId || (that.data.areaId == null)) {
      util.showModal('请选择区域');
      return
    }
    if (!that.data.buildid) {
      util.showModal('请选择楼栋');
      return
    }
    if (that.data.floorId==null) {
      util.showModal('请选择楼层');
      return
    }
    if (!that.data.address) {
      util.showModal('请填写地址');
      return
    }
    if (!that.data.applicationName) {
      util.showModal('请填写姓名');
      return
    }
    if (!that.data.applicantPhone) {
      util.showModal('请填写电话号码');
      return
    }
    if (!that.data.remark) {
      wx.showToast({
        title: '请填写报修原因',
      })
      return
    }
    if (that.data.sources.length <= 0) {
      util.showModal('请上传图片');
      return
    }
    var data = {
      applicantId: that.data.applicantId,
      applicantName: that.data.applicationName,
      applicantPhone: that.data.applicantPhone,
      buildingId: that.data.buildid,
      areaId: that.data.areaId,
      floorId: that.data.floorId,
      address: that.data.address,
      remark: that.data.remark,
      image: that.data.sources
    };
    // wx.request({
    //   url: applet_park_api_url + '/api/repairs',
    //   data: data,
    //   method: 'POST',
    //   success(res) {
    //     if (res.data.code == 0) {
    //       // wx.redirectTo({
    //       //   url: '../maintenanceList/maintenancelist',
    //       // })
    //       var pages = getCurrentPages();
    //       var prevPage = pages[pages.length - 2]; //上一个页面
    //       // prevPage.data.items = [];

    //       // prevPage.loadData();
    //       // prevPage.setData(prevPage.setDat);
    //       wx.navigateBack();
    //     } else {
    //       wx.showToast({
    //         title: '网络异常',
    //       })
    //     }
    //   },
    //   fail(res) {
    //     wx.showToast({
    //       title: res.data,
    //     })
    //   }
    // })

    requestDataparams('/api/repairs', data, 'POST').then(res => {
      if (res.data.code == 0) {
        // wx.redirectTo({
        //   url: '../maintenanceList/maintenancelist',
        // })
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        // prevPage.data.items = [];

        // prevPage.loadData();
        // prevPage.setData(prevPage.setDat);
        wx.navigateBack();
      } else {
        wx.showToast({
          title: '网络异常',
        })
      }
    }).catch(err => {

    });
  },
  submit: function () {
    var that = this;
    var sources = '';
    wx.showLoading({
      title: '',
      mask: true
    });
    var finished = true;
    // that.data.imageList = that.data.imageSingleList.concat(that.data.imageMultiList);
    for (var pic of that.data.imageList) {
      if (!pic.picUrl) { //false
        finished = false;
        break;
      }
    }

    if (finished) {
      wx.hideLoading();

      // wx.navigateBack();
      that.submitRepair();
      return;
    }

    //用自执行函数,来解决循环内部的异步回调问题
    (function uploadImage(i) {
      if (i >= that.data.imageList.length) {
        return;
      }

      // var image = that.data.imageList[i];
      if (!that.data.imageList[i].picUrl && that.data.imageList[i].path) {
        var path = that.data.imageList[i].path;
        wx.uploadFile({
          url: 'https://jinchengit.cn:9999/api/upload',
          filePath: path,
          name: 'files',
          success(res) {
            let response = JSON.parse(res.data);
            that.data.imageList[i].picUrl = applet_park_api_url + response.data[0];
            sources = sources + response.data + ",";
            that.data.sources = sources;
            that.setData(that.data);
            //检测下其他图片有没有传完
            var allFinished = true;
            for (var pic of that.data.imageList) {
              if (!pic.picUrl) { //false
                allFinished = false;
                break;
              }
            }
            if (allFinished) { //全部传完了,则隐藏加载按钮并返回
              wx.hideLoading();
              //数据回传录车页面,返回
              that.submitRepair();
              //wx.navigateBack();
            } else {
              uploadImage(i + 1);
            }
          },
          fail(res) {

          }
        })
      } else {
        uploadImage(i + 1);
      }
    })(0);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})